//
//  ActiveDetailViewController.m
//  yunyan
//
//  Created by haichuang on 2018/2/26.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "ActiveDetailViewController.h"
#import "ActiveDetailTopCell.h"
#import "CommentCell.h"

#import "InputView.h"
#import "ShareView.h"
@interface ActiveDetailViewController ()<UITableViewDelegate, UITableViewDataSource,XHInputViewDelagete>{
    
    UIButton * midBtn;
    NSString * likeStr;
    NSString * operation; // 收藏状态
    
    int page;
    NSMutableArray * _dataArray;
}

@property (nonatomic ,strong) UIImageView * imageView;
@property (nonatomic, strong) UITableView * activeDetailTab;
@property (nonatomic, strong)   UIView * GRbackgView;
@property (nonatomic, strong) ShareView *shareView;
@end

@implementation ActiveDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    page = 1;
    _dataArray = @[].mutableCopy;
     [self customNaviItemTitle:@"随手拍详情" isLeft:YES];
    [self customTabBarButtonTitle:nil image:[UIImage imageNamed:@"new_share_default"] target:self action:@selector(shareBtn) isLeft:NO];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(imageTap:)
                                                 name: @"imageTap"
                                               object:nil];
    
    [self createDetailUI];
    
//    [self getActDetailsRequest];
    
    [self getCommentListRequest];
}


-(void)imageTap:(NSNotification *)notification
{
    NSString  * tapTag = notification.object;
    
    TCLPhotoBrowserViewController *photo = [[TCLPhotoBrowserViewController alloc]init];
    
    photo.photos = USER_DEFAULTGet(@"actDetailsIamgeArray");
    photo.currentPage = [tapTag integerValue];
    [self presentViewController:photo animated:YES completion:nil];
   
}

-(void)createDetailUI{
   
    WeakSelf;
    _activeDetailTab = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:_activeDetailTab ];
    [_activeDetailTab mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.right.top.equalTo (weakSelf.view);
        make.bottom.equalTo (weakSelf.view.mas_bottom).offset (-50.0f);

    }];
   
    self.activeDetailTab.estimatedRowHeight = 44.f;
    self.activeDetailTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.activeDetailTab.rowHeight = UITableViewAutomaticDimension;
    _activeDetailTab.delegate = self;
    _activeDetailTab.dataSource = self;
    [_activeDetailTab registerNib:[UINib nibWithNibName:@"CommentCell" bundle:nil] forCellReuseIdentifier:@"CommentCell"];
    [_activeDetailTab registerClass:[ActiveDetailTopCell class] forCellReuseIdentifier:@"ActiveDetailTopCell"];
   
    
    UIView * buttomView = [[UIView alloc] init];
    [buttomView setViewRoundShadow];
      buttomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:buttomView];
    [buttomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo (weakSelf.view);
        make.height.equalTo (@(50.f));
    }];
    UITapGestureRecognizer * neargrGes=[[UITapGestureRecognizer  alloc]initWithTarget:self action:@selector(bottomGes)];
    [buttomView addGestureRecognizer:neargrGes];
    
    UIImageView *imageView = [[UIImageView alloc] init];
    [buttomView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo (buttomView).offset (18.0f);
        make.width.height.equalTo (@(14.0f));
       
    }];
    imageView.image = [UIImage imageNamed:@"new_input_default"];
    UILabel * label = [[UILabel alloc]init];
    [buttomView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo (imageView.mas_right).offset (6.0f);
        make.top.bottom.equalTo (imageView);
        
    }];
    label.text = @"畅言一下...";
    label.font = [UIFont boldSystemFontOfSize:12.0];
    label.textColor = RGBA(51, 51, 51, 1);
    
    
  
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)bottomGes{
    [self showXHInputViewWithStyle:InputViewStyleLarge];
}

#pragma mark- share
-(void)shareBtn{
    
    NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    
    if (user_id.length>1) {
        [self CreateShareViewAppear];
        
    }else {
        LoginViewController *loginVC = [LoginViewController new];
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:navc animated:YES completion:nil];
    }
    
}

-(void)CreateShareViewAppear{
    
    WeakSelf;
    self.navigationItem.rightBarButtonItem.enabled = NO;
    _GRbackgView = [[UIView alloc] init];
    
    [self.view addSubview:_GRbackgView];
    [_GRbackgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.equalTo(weakSelf.view);
        
    }];
    
    _GRbackgView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.10];
    [self.view addSubview:_GRbackgView];
    
    _shareView = [[ShareView alloc]init];
    
    [self.view addSubview:_shareView];
    
    
    [_shareView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(weakSelf.view);
        make.height.equalTo(@200);
        make.bottom.equalTo(weakSelf.view.mas_bottom);
    }];
    _shareView.backgroundColor = [UIColor whiteColor];
    
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = _shareView.frame;
        frame.origin.y = -200;
        
        [_shareView setFrame:frame];
        
        
    } completion:^(BOOL finished) {
        
    }];
    _shareView.cancelBlock = ^{
        [weakSelf geGes];
    };
    
    UITapGestureRecognizer * neargrGes=[[UITapGestureRecognizer  alloc]initWithTarget:self action:@selector(geGes)];
    [_GRbackgView addGestureRecognizer:neargrGes];
    
}



-(void)geGes{
    
    
    [UIView animateWithDuration:0.8 animations:^{
        
        
        _shareView.alpha = 0.0;
        _GRbackgView.alpha = 0.0;
        
    } completion:^(BOOL finished) {
        
        [_shareView removeFromSuperview];
        [_GRbackgView removeFromSuperview];
        
         self.navigationItem.rightBarButtonItem.enabled = YES;
    }];

}

#pragma mark - tableview delegete;
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section  == 1) {
        return _dataArray.count;
    }
   else{
       return 1;
   }

}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        
        return  60;
    }else{
       
        return CGFLOAT_MIN;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   
    if (section == 1) {
        
        UIView * view = [[UIView alloc]init];
        UIImageView * image = [[UIImageView alloc] init];
        image.backgroundColor = [UIColor whiteColor];
        [view addSubview:image];
        [image mas_makeConstraints:^(MASConstraintMaker *make) {
            
//            make.left.equalTo (view.mas_left).offset (80.0f);
//            make.right.equalTo (view.mas_right).offset (-80.0f);
//            make.top.equalTo (view.mas_top).offset (10.0f);
//            make.height.equalTo (image.mas_width).multipliedBy(30/144);
            make.centerX .equalTo (view.mas_centerX);
            make.height.equalTo (@(30.f));
            make.width .equalTo (@(144.f));
            make.top.equalTo (view.mas_top).offset (24.f);
            
        }];
        image.image = [UIImage imageNamed:@"new_title_pressed"];
         view.backgroundColor = [UIColor whiteColor];
        return view;
    }else {
       
        return nil;
    }
   
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    return nil;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section == 0) {
        
        ActiveDetailTopCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ActiveDetailTopCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
//        [cell.topHeaderView.headImage sd_setImageWithURL:ImageUrl(self.dataDic[@"head_url"]) placeholderImage:ImageName(@"img_head_portrait_pre")];
        
        
//        cell.nameTitleLabel.text = self.dataDic[@"user_nick"];
//        cell.timeLabel.text = self.dataDic[@"create_time"];
        
         UILabel *   _nameTitleLabel = [[UILabel alloc] init];
        [cell.shHeardView addSubview:_nameTitleLabel];
        [_nameTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo (cell.headImage);
            make.left.equalTo (cell.headImage.mas_right).offset (9.0f);
        }];
        _nameTitleLabel.textColor = RGBA(51, 51, 51, 1);
        _nameTitleLabel.font = [UIFont systemFontOfSize:18.0f];
        _nameTitleLabel.text = self.dataDic[@"user_nick"];
        
        UILabel *  _timeLabel = [[UILabel alloc] init];
        [cell.shHeardView addSubview:_timeLabel];
        [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo (cell.headImage);
            make.right.equalTo (cell.mas_right).offset (-20.0f);
        }];
        _timeLabel.textColor = RGBA(153, 153, 153, 1);
        _timeLabel.font = [UIFont systemFontOfSize:12.0f];
        _timeLabel.text = self.dataDic[@"create_time"];
        
        
        [cell.headImage sd_setImageWithURL:ImageUrl(self.dataDic[@"head_url"]) placeholderImage:ImageName(@"img_head_portrait_pre")];
        
        cell.imageArray = self.dataDic[@"pic_url"];
         [cell.likeBtn addTarget:self action:@selector(likeBtnClicked) forControlEvents:UIControlEventTouchUpInside];
        
        int sele = [USER_DEFAULTGet(@"act_is_fabulous") intValue];
        if (sele == 0) {
            operation = @"1";
        }else {
            operation = @"2";
        }
        
        if ([self.dataDic[@"is_fabulous"] intValue] ==1) {
            [cell.likeBtn setImage:[UIImage imageNamed:@"new_praise_pressed"] forState:UIControlStateNormal];
            [cell.likeBtn setTitle:@" 取消点赞" forState:UIControlStateNormal];
            [cell.likeBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }else{
            [cell.likeBtn setImage:[UIImage imageNamed:@"new_praise_default"] forState:UIControlStateNormal];
            [cell.likeBtn setTitle:@"点赞" forState:UIControlStateNormal];
            [cell.likeBtn setTitleColor:RGBA(102, 102, 102, 1)forState:UIControlStateNormal];
            
        }
        midBtn = cell.likeBtn;
        cell.titlelLabel.text = self.dataDic[@"title"];
        cell.detailLabel.text = self.dataDic[@"content"];
        
        return cell;
        
        
    }else {
        
    NSDictionary * dic = _dataArray[indexPath.row];
    CommentCell * cell=[tableView dequeueReusableCellWithIdentifier:@"CommentCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    [cell.image sd_setImageWithURL:ImageUrl(dic[@"head_url"]) placeholderImage:ImageName(@"")];
        cell.nameLabel.text = dic[@"user_nick"];
        cell.conteLabel.text = dic[@"content"];
        
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    }
}

-(void)likeBtnClicked {
    
    NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    if (user_id.length>1) {
        [self setCollectRequest];
    }else {
        LoginViewController *loginVC = [LoginViewController new];
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:navc animated:YES completion:nil];
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    if (indexPath.section == 2) {
//
//        [self showXHInputViewWithStyle:InputViewStyleLarge];
//    }else{
//
//        return;
//    }
}

-(void)showXHInputViewWithStyle:(InputViewStyle)style{
    
    [InputView showWithStyle:style configurationBlock:^(InputView *inputView) {
        /** 请在此block中设置inputView属性 */
        
        /** 代理 */
        inputView.delegate = self;
        
        /** 占位符文字 */
        // inputView.placeholder = @"请输入评论文字噢噢噢噢";
        /** 设置最大输入字数 */
        inputView.maxCount = 50;
        /** 输入框颜色 */
        inputView.textViewBackgroundColor = [UIColor groupTableViewBackgroundColor];
        
        /** 更多属性设置,详见XHInputView.h文件 */
        
    } sendBlock:^BOOL(NSString *text) {
        if(text.length){
            NSLog(@"输入的信息为:%@",text);
            [self publishCommentRequestForStr:text];
            return YES;//return YES,收起键盘
        }else{
            NSLog(@"显示提示框-请输入要评论的的内容");
            SHuiMBhudTextTimeStr(@"请输入要评论的的内容");
            return NO;//return NO,不收键盘
        }
    }];
}

//获取详情
-(void)getActDetailsRequest{
    
    NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    if (user_id.length>1) {
        
    }else {
        user_id = @"";
    }
    
    
    NSDictionary * dic = @{@"news_id":self.actIdStr,
                           @"user_id":user_id
                           };
    
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(activity_details_api) andparameters:dic Success:^(id responseObject) {
        
        self.self.dataDic = responseObject;
        
        NSLog(@"responseObject = %@",responseObject);
        
        USER_DEFAULTSet(self.dataDic[@"pic_url"], @"actDetailsIamgeArray");
         USER_DEFAULTSet(self.dataDic[@"is_fabulous"], @"act_is_fabulous");
        
    
        if ([self.dataDic[@"pic_url"] isKindOfClass:[NSArray class]]) {
            NSArray * array = self.dataDic[@"pic_url"];
            if (array.count==0) {
                
                USER_DEFAULTSet(@"http://a1.qpic.cn/psb?/V147v55d35m6eX/xXdZ2De4s1iE5gYJaikuWyqltDsmFf*LHHZ1ANFPtso!/m/dDABAAAAAAAA&bo=eAB4AAAAAAADByI!&rf=photolist", @"shareImage");
            }else {
                
                 USER_DEFAULTSet(self.dataDic[@"pic_url"][0], @"shareImage");
            }
        }
        NSString * newsId= [NSString stringWithFormat:@"%ld",[self.dataDic[@"id"] integerValue]];
        USER_DEFAULTSet(newsId,@"shareNewsId");
        USER_DEFAULTSet(@"2",@"shareType");
        USER_DEFAULTSet(self.dataDic[@"title"], @"shareTitle");
        USER_DEFAULTSet(self.dataDic[@"content"], @"shareContent");
        USER_DEFAULTSet(self.dataDic[@"share_url"], @"shareUrl");
        
        if ([self.dataDic[@"is_fabulous"] intValue] ==1) {
            [midBtn setImage:[UIImage imageNamed:@"new_praise_pressed"] forState:UIControlStateNormal];
            [midBtn setTitle:@" 取消点赞" forState:UIControlStateNormal];
            [midBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }else{
            [midBtn setImage:[UIImage imageNamed:@"new_praise_default"] forState:UIControlStateNormal];
            [midBtn setTitle:@"点赞" forState:UIControlStateNormal];
            [midBtn setTitleColor:RGBA(102, 102, 102, 1)forState:UIControlStateNormal];
            
        }
        
        if ([likeStr isEqualToString:@"mark"]) {

        }else{
            [_activeDetailTab reloadData];
        }
//         [_activeDetailTab  scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        [_activeDetailTab.mj_header endRefreshing];
        [_activeDetailTab.mj_footer endRefreshing];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
    
}
//设置收藏
-(void)setCollectRequest{
    
    
    
    int sele = [USER_DEFAULTGet(@"act_is_fabulous") intValue];
    if (sele == 0) {
       operation = @"1";
    }else {
       operation = @"2";
    }
    
    NSDictionary * dic = @{@"news_id":self.actIdStr,
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"token":USER_DEFAULTGet(@"token"),
                           @"operation":operation,
                           @"type":@"2"
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(collect_api) andparameters:dic Success:^(id responseObject) {
        
//        [self getActDetailsRequest];
        likeStr = @"mark";
//        [_activeDetailTab reloadData];
        
        if ([operation intValue] ==1) {
            [midBtn setImage:[UIImage imageNamed:@"new_praise_pressed"] forState:UIControlStateNormal];
            [midBtn setTitle:@" 取消点赞" forState:UIControlStateNormal];
            [midBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            USER_DEFAULTSet(@"1", @"act_is_fabulous");
        }else{
            [midBtn setImage:[UIImage imageNamed:@"new_praise_default"] forState:UIControlStateNormal];
            [midBtn setTitle:@"点赞" forState:UIControlStateNormal];
            [midBtn setTitleColor:RGBA(102, 102, 102, 1)forState:UIControlStateNormal];
            USER_DEFAULTSet(@"0", @"act_is_fabulous");
            
        }
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        [_activeDetailTab.mj_header endRefreshing];
        [_activeDetailTab.mj_footer endRefreshing];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            
            SHuiMBhudTextTimeStr(@"文章不存在");
        }else if(responses.statusCode == 403){
             SHuiMBhudTextTimeStr(@"已经点赞");
        }else if(responses.statusCode == 500){
            SHuiMBhudTextTimeStr(@"点赞失败");
        }else {
            SHuiMBhudTextTimeStr(@"请稍后再试");
        }
    }];
    
}


-(void)getCommentListRequest{

    NSDictionary * dic = @{@"news_id":self.actIdStr,
                           @"page":[NSString stringWithFormat:@"%d",page],
                           @"type":@"2"
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_commentList_api) andparameters:dic Success:^(id responseObject) {
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray * array = responseObject;
            
            if (page == 1) {
                if (_dataArray) {
                    [_dataArray removeAllObjects];
                }
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }else {
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }

         [_activeDetailTab reloadData];
        }
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        
        [_activeDetailTab.mj_header endRefreshing];
        [_activeDetailTab.mj_footer endRefreshing];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            NSLog(@"没有数据");
        }else {
            SHuiMBhudTextTimeStr(@"请稍后再试");
        }
    }];
    
}




#pragma mark - XHInputViewDelagete
/** XHInputView 将要显示 */
-(void)xhInputViewWillShow:(InputView *)inputView{
    
    /** 如果你工程中有配置IQKeyboardManager,并对XHInputView造成影响,请在InputView将要显示时将其关闭 */
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].enable = NO;
    
}

/** XHInputView 将要影藏 */
-(void)xhInputViewWillHide:(InputView *)inputView{
    
    /** 如果你工程中有配置IQKeyboardManager,并对XHInputView造成影响,请在XHInputView将要影藏时将其打开 */
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].enable = YES;
}

// 发布评论
-(void)publishCommentRequestForStr:(NSString *)str{
    
    
    NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    if (user_id.length>1) {
        NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                               @"news_id":self.actIdStr,
                               @"mac_code":[SHJudgeTools getDeviceId],
                               @"token":USER_DEFAULTGet(@"token"),
                               @"type":@"2",
                               @"content":str
                               };
        
        [PostNetWorking postNetWorkingStr:RequestUrlStr(publish_comment_api) andparameters:dic Success:^(id responseObject) {
            
            SHuiMBhudTextTimeStr(@"发送成功！");
            page =1;
            [self getCommentListRequest];
            [_activeDetailTab reloadData];
        } failed:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            
            if (responses.statusCode == 404) {
                SHuiMBhudTextTimeStr(@"未获取到数据");
            }else if (responses.statusCode==403){
                SHuiMBhudTextTimeStr(@"评论1分钟内只能提交一次");
            }else {
                SHuiMBhudTextNetError;
            }
        }];
        
    }else {
        LoginViewController *loginVC = [LoginViewController new];
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:navc animated:YES completion:nil];
    }
    
   
}


@end
